package com.ikun.lease.common.utils;

import com.ikun.lease.common.result.ResultCodeEnum;
import com.ikun.lease.common.exception.LeaseException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JWTutils {

    private static SecretKey secretKey = Keys.hmacShaKeyFor("ikundamnwhatcanisaymanxiaoheizig".getBytes());

    public static String createToken(Long userId,String username){

        String jwt = Jwts.builder().
                setExpiration(new Date(System.currentTimeMillis() + 3600000)).
                setSubject("USER_INFO").
                claim("userId", userId).
                claim("username", username).
                signWith(secretKey, SignatureAlgorithm.HS256).
                compact();

        return jwt;
    }
    public static Claims parseToken(String token){
        if(token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJwt = jwtParser.parseClaimsJws(token);
            return claimsJwt.getBody();
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

}
